package org.sql.jdbc.datasource;

import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import com.alibaba.druid.pool.DruidDataSource;

/** 
 * jdbc连接池
 *
 * <pre> 
 * 构建组：e-jdbc
 * 作者：eddy
 * 邮箱：1546077710@qq.com
 * 日期：2017年4月23日-下午9:49:21
 * 版权：E源时代
 * </pre>
 */
public class JdbcSupport {

	// 定义一个连接池对象变量
	private static DruidDataSource dataSource = null;
	private static final String CONFIG_PATH = "conf"+File.separator+"db-config.properties";
	
	private static void init(){
		try {
			InputStream inStream = null;
			ClassLoader cl = JdbcSupport.class.getClassLoader();
			if (cl != null) {
				inStream = cl.getResourceAsStream(CONFIG_PATH);
			} else {
				inStream = ClassLoader.getSystemResourceAsStream(CONFIG_PATH);
			}
			Properties props = new Properties();
			props.load(inStream);

			// Create Pool
			dataSource = new DruidDataSource();
			dataSource.setDriverClassName(props.getProperty("db.driver.className"));
			dataSource.setUrl(props.getProperty("db.url"));
			dataSource.setUsername(props.getProperty("db.username"));
			dataSource.setPassword(props.getProperty("db.password"));
		} catch (Exception e) {
			org.apache.log4j.Logger.getLogger(JdbcSupport.class).error("", e);
		}
	}

	/**
	 * 获取一个Connection对象
	 * 
	 * @return
	 * @throws Exception
	 */
	public synchronized static Connection getConnection() {
		Connection con = null;
		try {
			if(null==dataSource){
				init();
			}
			
			con = dataSource.getConnection();
		} catch (SQLException e) {
			org.apache.log4j.Logger.getLogger(JdbcSupport.class).error("", e);
		}
		return con;
	}

	/**
	 * 释放connection和statement资源
	 * 
	 * @param con
	 * @param stat
	 */
	public static void close(Connection con, Statement stat) {
		close(stat);// 释放statement
		close(con);// 释放connection
	}

	/**
	 * 释放Connection,Statment,ResultSet
	 * 
	 * @param con
	 * @param stat
	 * @param rs
	 */
	public static void close(Connection con, Statement stat, ResultSet rs) {
		close(rs);
		close(stat);
		close(con);
	}

	private static void close(ResultSet rs) {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				org.apache.log4j.Logger.getLogger(JdbcSupport.class).error("",
						e);
			}
		}
	}

	private static void close(Statement stat) {
		if (stat != null) {
			try {
				stat.close();
			} catch (SQLException e) {
				org.apache.log4j.Logger.getLogger(JdbcSupport.class).error("",
						e);
			}
		}
	}

	public static void close(Connection con) {
		if (con != null) {
			try {
				con.close();
			} catch (SQLException e) {
				org.apache.log4j.Logger.getLogger(JdbcSupport.class).error("",
						e);
			}
		}
	}
}
